/**
 * 
 */
package pt.mleiria.experiments;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

/**
 * @author NB13712
 *
 */
public class CAPTokenComputation {
	
	private static String ipbStr = "00007fffff00000000000000000000000000";
	private static byte[] ipb;	
	
	public String getIpbStr() {
		return ipbStr;
	}

	public static void setIpbStr(String ipbStr) {
		CAPTokenComputation.ipbStr = ipbStr;
	}

	public static byte[] getIpb() {
		try {
			char[] ipbChar = ipbStr.toCharArray();
			ipb = Hex.decodeHex(ipbChar);
			return ipb;
		} catch (DecoderException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void setIpb(byte[] ipb) {
		CAPTokenComputation.ipb = ipb;
	}

	public static byte[] decompressToken(long token) {
		return decompressToken(token, ipb);
	}
	/**
     * Decompresses an EMV-CAP <code>token</code> according to the <em>Issuer
     * Proprietary Bitmap</em> <code>ipb</code>.
     *
     * @param token EMV-CAP token to be decompressed.
     * @param ipb <em>Issuer Proprietary Bitmap</em>.
     * @return A decompressed EMV-CAP token.
     */
    public static byte[] decompressToken(long token, byte[] ipb) {
        byte[] partialToken = new byte[ipb.length];
        int tokenBitMask = 1;
 
        for(int i = ipb.length - 1; i >= 0 ; i--) {
            for(int mask = 1; mask < 0x100; mask <<= 1) {
                if((ipb[i] & mask) > 0) {
                    if((token & tokenBitMask) > 0) {
                        partialToken[i] |= mask;
                    }
                    tokenBitMask <<= 1;
                }
            }
        }
 
        return partialToken;
    }
    
    public static byte[] atcDerivation(){
    	
    	return null;
    }
 
}
